{% extends 'sales/base.html' %}
{% load static %}
{% block breadcrumb %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'opportunities:list' %}">Opportunities</a></li>
    <li class="breadcrumb-item active">{% if opportunity_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock %}
{% block content %}

<head>
  <link rel="stylesheet" type="text/css"
    href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/start/jquery-ui.css" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-tagsinput/1.3.6/jquery.tagsinput.min.css" rel="stylesheet">
</head>
<form id="id_opportunity_form" class="form_user" method="POST" action="" novalidate enctype="multipart/form-data">
  <div class="overview_form_block row marl justify-content-center">
    <div class="col-md-9">
      <div class="card">
        <div class="card-body">
          <div class="card-title text-center">
            {% if opportunity_obj %}EDIT{% else %}CREATE{% endif %} OPPORTUNITY
          </div>
          <div class="row marl no-gutters">
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1"
                    class="required">Name{% if opportunity_form.name.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ opportunity_form.name }}
                  <span class="error error_message" id="error_id_name">{{opportunity_form.name.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Account{% if opportunity_form.account.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {% if account %}
                  <select name="account" placeholder="Account" class="form-control" id="id_account" readonly>
                    <option value="{{account.id}}" selected="">{{account.name}}</option>
                  </select>
                  {% else %}
                  {{opportunity_form.account}}
                  {% endif %}
                  <span class="error error_message" id="error_id_account">{{opportunity_form.account.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Amount</label>
                  {{ opportunity_form.amount }}
                  <span class="error error_message" id="error_id_amount">{{opportunity_form.amount.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Currency</label>
                  <select name="currency" id="id_currency" class="form-control">
                    <option value="">----------</option>
                    {% for currency in currencies %}
                    <option value="{{currency.0}}" {% if opportunity_obj.currency == currency.0 %} selected=""
                      {% endif %}>{{currency.1}}</option>
                    {% endfor %}
                  </select>
                  <span class="error error_message" id="error_id_currency">{{opportunity_form.currency.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1"
                    class="required">Stage{% if opportunity_form.stage.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ opportunity_form.stage }}
                  <span class="error error_message" id="error_id_stage">{{opportunity_form.stage.errors}}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Lead Source{% if opportunity_form.lead_source.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ opportunity_form.lead_source }}
                  <span class="error error_message"
                    id="error_id_lead_source">{{opportunity_form.lead_source.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Probability %{% if opportunity_form.probability.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ opportunity_form.probability }}
                  <span class="error error_message"
                    id="error_id_probability">{{opportunity_form.probability.errors}}</span>
                </div>
              </div>
              {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus">Teams{% if opportunity_form.teams.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                    {% for team in teams %}
                    <option data-users="{{team.get_users}}" value="{{team.id}}"
                      {% if team in opportunity_obj.teams.all %} selected="" {% endif %}>
                      {{team}}</option>
                    {% endfor %}
                  </select>
                  <span class="error" id="id__teams">{{ opportunity_form.teams.errors }}</span>
                </div>
              </div>

              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus"><span class="">Users</span></label>
                  <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                    {% if opportunity_obj and opportunity_obj.teams.all %}
                    {% for user in users %}
                    {% if user in opportunity_obj.get_team_users %}
                    <option value="{{user.id}}" selected="">{{user.email}}</option>
                    {% else %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    {% for user in users %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endfor %}
                    {% endif %}
                  </select>
                </div>
              </div>

              {% endif %}
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Assigned Users</label>
                  <select class="assigned_users form-control" name="assigned_to" multiple="multiple"
                    id="id_assigned_to">
                    {% for user in users %}
                    <option value="{{user.id}}"
                      {% if user in opportunity_obj.get_assigned_users_not_in_teams or user.id in assignedto_list %} selected=""
                      {% endif %}>{{user.email}}</option>
                    {% endfor %}
                  </select>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Contacts{% if opportunity_form.contacts.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ opportunity_form.contacts }}
                  <span class="error error_message" id="error_id_contacts">{{opportunity_form.contacts.errors}}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Due Date{% if opportunity_form.closed_on.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <div class='input-group date' id='datepicker1'>
                    {{ opportunity_form.closed_on }}
                    <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                  </div>
                  <span class="error error_message" id="error_id_closed_on">{{opportunity_form.closed_on.errors}}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col col-12">
                <div class="form-group">
                  <label>Tags</label>
                  <div class="txt-box-div" id="tag-div"><input type="text" name="tags" id="tags_1"
                      value="{% for t in opportunity_obj.tags.all %}{{t.name}}, {% endfor %}" class="tags" />
                  </div>
                </div>
              </div>
              <div class="form-group col-md-12">
                <label for="exampleInputEmail1">Description{% if opportunity_form.description.field.required %}<span
                    class="error">*</span>{% endif %}</label>
                {{ opportunity_form.description }}
                <span class="error error_message"
                  id="error_id_description">{{opportunity_form.description.errors}}</span>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Attachment</label>
                  <input type="file" name="oppurtunity_attachment" id="oppurtunity_attachment">
                  {% if opportunity_obj.opportunity_attachment.count %}
                  {% for attachment in opportunity_obj.opportunity_attachment.all %}
                  <div id="attachment{{attachment.id}}" class="mt-2">
                    <a target="_blank" href="{{ attachment.attachment.url }}">{{ attachment.file_name }}</a>
                    {% if not attachment.created_by.role == 'ADMIN' or attachment.created_by.role == request.user.role %}
                    <a class="action btn primary_btn" onclick="remove_attachment({{attachment.id}})">X</a>
                    {% endif %}
                  </div>
                  {% endfor %}
                  {% endif %}
                  <span class="error"></span>
                </div>
              </div>
            </div>
          </div>
          <br clear="all">
          <input type="hidden" name="from_account" value="{{request.GET.view_account}}">
          {% if request.GET.view_account %}
          <input type="hidden" name="account" value="{{request.GET.view_account}}">
          {% endif %}
          <input type="hidden" id="save_new_form" name="savenewform">
        </div>
        
        <div class="row marl buttons_row text-center form_btn_row">
          <button class=" btn btn-default save" type="submit" id="submit_btn">Save</button>
          {% if not opportunity_obj %}
          <button class="btn btn-success save savenew" type="submit">Save & New</button>
          {% endif %}
          <a {% if request.GET.view_account %} href="{% url 'accounts:view_account' request.GET.view_account %}"
            {% else %} href="{% url 'opportunities:list' %}" {% endif %} class="btn btn-default clear">Cancel</a>
        </div>
      </div>
    </div>
  </div>
</form>
<div class="row marl justify-content-center text-center mt-5 mb-5" id="progress_bar">
  
  <div class="progress position-relative" style="width:40%;height:1.5rem;">
    <span class="justify-content-center d-flex position-absolute w-100 percent">0%</span>
    <div class="progress-bar bar"></div>
  </div>
</div>
{% endblock %}
{% block js_block %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript">
  var bar = $('.bar');
  var percent = $('.percent');

  $('#progress_bar').hide()
  $('#_id_assigned_to').select2({ disabled: 'readonly' });

  $('form#id_opportunity_form').ajaxForm({
    type: 'POST',
    dataType: 'json',
    url: ".",
    data: $('#id_opportunity_form').serialize(),
    beforeSubmit: disableButton,
    beforeSend: function () {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    uploadProgress: function (event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal);
      if (percentVal == '100%') {
        percent.html('Uploading ...')
      }
      else {
        percent.html(percentVal);
      }
    },
    success: function (data) {
      if (data.error) {
        $('#progress_bar').hide()
        $('.error_message').html('')
        for (var key in data.errors) {
          $('#error_id_' + key).html("<p>" + data.errors[key][0] + "</p>");
        };
        $('#submit_btn').removeAttr('disabled')
      }
      else {
        window.location = data.success_url;
      }
    }
  });

  $('#submit_btn').click(function () {
    var file = $('#oppurtunity_attachment')[0].files[0];
    if (file && file.name.length > 0) {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
      $('#progress_bar').show()
    }

  });

  function disableButton() {
    // $('#progress_bar').show()
    $('#submit_btn').attr('disabled', 'disabled')
  }

  $(function () {
    var date = new Date();
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    $('#id_closed_on').datetimepicker({
      'format': 'YYYY-MM-DD',
      minDate: today
    })
  });

  $(".savenew").on('click', function (e) {
    e.preventDefault()
    $("#save_new_form").val('true')
    $('#id_opportunity_form').submit()
  });
  $(document).ready(function () {
    $('.assigned_users').select2();
    $("#id_contacts").select2();
    $('#id_currency').select2();
    $('#id_teams').select2();
  });

  $('#id_account').change(function () {
    var Account = $("#id_account").val()
    $.get("{% url 'opportunities:contacts' %}", { "Account": Account }, function (data) {
      $("#id_contacts").html("")
      $.each(data, function (index, value) {
        $("#id_contacts").append("<option value=" + index + ">" + value + "</option>")
      });
    })
  });

  $("#comment_form").submit(function (e) {
    e.preventDefault()
    var formData = new FormData($("#comment_form")[0]);
    $.ajax({
      url: "{% url 'opportunities:add_comment' %}",
      type: "POST",
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      success: function (data) {
        if (data.error) {
          $("#CommentError").html(data.error).show()
        }
        else {
          $("#comments_div").prepend("<li class='list-group-item list-row' id='comment" + data.com_id + "'>" +
            "<div class='pull-right right-container'>" +
            "<div class='list-row-buttons btn-group pull-right'>" +
            "<button class='btn btn-link btn-sm dropdown-toggle' data-toggle='dropdown' type='button'><span class='caret'></span></button>" +
            "<ul class='dropdown-menu pull-right'>" +
            "<li><a class='action' onclick='edit_comment(" + data.com_id + ")'>Edit</a></li>" +
            "<li><a class='action' onclick='remove_comment(" + data.com_id + ")''>Remove</a></li></ul></div></div>" +
            "<div class='stream-head-container'> " + data.com_user + " Commented</div>" +
            "<div class='stream-post-container' id='comment_name" + data.com_id + "'>" + data.comment + "</div>" +
            "<div class='stream-date-container" + data.com_id + "'>" + data.comment_time + "</div></div><div class='stream-date-container' id='comment_file_div" + data.com_id + "'><div id='new_comment" + data.com_id + "'</div></div></li>"
          )
          $("#id_comments").val("")
          alert("Comment Submitted")
        }
      }
    });
  });


  function edit_comment(x) {
    $('#myModal_comment').modal('show');
    comment = $("#comment_name" + x).text()
    $("#commentid").val(x)
    $("#id_editcomment").val(comment)
  }

  $("#comment_edit").click(function (e) {
    alert("Heyyyyyyyyyyy")
    e.preventDefault()
    var formData = new FormData($("#comment_edit_form")[0]);
    $.ajax({
      url: "{% url 'opportunities:edit_comment' %}",
      type: "POST",
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      success: function (data) {
        if (data.error) {
          alert(data.error)
        } else {
          $("#comment_name" + data.commentid).text(data.comment)
          $('#myModal_comment').modal('hide');
          $("#id_editcomment").val("")
        }
      }
    })
  });

  function remove_comment(x) {
    var warn = confirm("Are You Sure, you Want to Delete this Comment!?")
    if (warn == true) {
      $.post('{% url "opportunities:remove_comment" %}', { "comment_id": x }, function (data) {
        if (data.error) {
          alert(data.error)
        } else {
          $("#comment" + data.oid).remove()
        }
      })
    }
  }

  function editFun(x) {
    $.ajax({
      type: "POST",
      url: "/opportunities/editdetails/",
      data: { tid: x },
      success: function (data) {
        $("#viewdiv").hide()
        $("#editdiv").show()
        $("#id_name").val(data.name)
        $("#id_stage").val(data.stage)
        $("#id_amount").val(data.amount)
        $("#id_account").val(data.account)
        $("#id_probability").val(data.probability)
        $("#id_close_date").val(data.close_date)
        $("#hiddenval").val(data.eid)
        $("#id_lead_source").val(data.sources)
        $("#id_description").val(data.description)
        contacts = data.contacts.replace("b'", "")
        contacts = contacts.replace(/\\n/g, '')
        contacts = contacts.replace(/\\t/g, '')
        contacts = contacts.replace(/'/g, '')
        contacts = contacts.replace(/}/g, '')
        $("#id_contacts").html(contacts)
      }
    })


    $('#id_account').change(function () {
      var Account = $("#id_account").val()
      $.get("{% url 'opportunities:contacts' %}", {
        "Account": Account
      }, function (data) {
        $("#id_contacts").html("")
        $.each(data, function (index, value) {
          // console.log(index, value)
          $("#id_contacts").append("<option value=" + index + ">" + value + "</option>")
        });
      })
    });

  }
  function onAddTag(tag) {
    alert("Added a tag: " + tag);
  }
  function onRemoveTag(tag) {
    alert("Removed a tag: " + tag);
  }

  function onChangeTag(input, tag) {
    alert("Changed a tag: " + tag);
  }

  $(function () {

    $('#tags_1').tagsInput({ width: 'auto' });
    $('#tags_2').tagsInput({
      width: 'auto',
      onChange: function (elem, elem_tags) {
        var languages = ['php', 'ruby', 'javascript'];
        $('.tag', elem_tags).each(function () {
          if ($(this).text().search(new RegExp('\\b(' + languages.join('|') + ')\\b')) >= 0)
            $(this).css('background-color', 'yellow');
        });
      }
    });
    $('#tags_3').tagsInput({
      width: 'auto',

      //autocomplete_url:'test/fake_plaintext_endpoint.html' //jquery.autocomplete (not jquery ui)
      autocomplete_url: 'test/fake_json_endpoint.html' // jquery ui autocomplete requires a json endpoint
    });


    // Uncomment this line to see the callback functions in action
    //      $('input.tags').tagsInput({onAddTag:onAddTag,onRemoveTag:onRemoveTag,onChange: onChangeTag});   

    // Uncomment this line to see an input with no interface for adding new tags.
    //      $('input.tags').tagsInput({interactive:false});
  });

  function remove_attachment(x) {
    const con = confirm("Do you want to Delete it for Sure!?");
    if (con == true) {
      $.post('{% url "cases:remove_attachment" %}', {
        "attachment_id": x
      }, function (data) {
        if (data.error) {
          alert(data.errors)
        } else {
          $("#attachment" + data.attachment_object).remove()
        }
      })
    }
  }

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'opportunities:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {

    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'leads:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )

          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}